from flask import Flask
import redis

class RedisExtension:
    def __init__(self, app=None):
        self.redis_client = None
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Flask):
        """初始化Redis连接"""
        redis_config = {
            'host': app.config.get('REDIS_HOST', 'localhost'),
            'port': app.config.get('REDIS_PORT', 6379),
            'db': app.config.get('REDIS_DB', 0),
            'password': app.config.get('REDIS_PASSWORD'),
            'decode_responses': app.config.get('REDIS_DECODE_RESPONSES', True)
        }

        # 创建Redis连接
        try:
            self.redis_client = redis.Redis(**redis_config)
        except Exception as e:
            self.redis_client = None

    # 将Redis客户端的常用方法代理到RedisExtension类中
    def __getattr__(self, name):
        return getattr(self.redis_client, name)

redis_store = RedisExtension()